<template>
  <div class="box">
    <el-form :model="form" label-width="120px" v-loading="loading" status-icon :rules="rules" ref="formRef">
      <div style="display: inline-block">
        <el-form-item label="商品名" prop="name">
          <el-input v-model="form.name" style="width: 200px;" />
        </el-form-item>
      </div>
      <div style="display: inline-block" >
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="form.price" style="width: 200px;" />
        </el-form-item>
      </div>
      <div style="display: inline-block" >
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" style="width: 200px;" />
        </el-form-item>
      </div>
      <div style="display: inline-block" >
        <el-form-item label="商品分类" prop="itemCategoryId">
          <el-input v-model="form.itemCategoryId" style="width: 200px;" />
        </el-form-item>
      </div>
      <el-form-item label="商品描述">
        <el-input v-model="form.description" type="textarea" style="width: 300px;" rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onInsert">插入</el-button>
        <el-button >退出</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { reactive } from 'vue';
import { createItem } from "@/api/item";
import { ElMessage } from 'element-plus';
export default {
  name: "itemInsert",
  data() {
    return {
      // do not use same name with ref
      form: reactive({
        name: '',
        price: '',
        stock: '',
        itemCategoryId: '',
        description: '',
      }),
      loading: false,
      rules:{
        name:[
          {required: true, message: '请输入商品名', trigger: 'blur'}
        ],
        price:[
          {required: true, message: '请输入价格', trigger: 'blur'}
        ],
        stock:[
          {required: true, message: '请输入库存', trigger: 'blur'}
        ],
        itemCategoryId:[
          {required: true, message: '请输入商品分类', trigger: 'blur'}
        ],
      }
    }
  },
  methods: {
    //提交修改
    onInsert() {
      this.$refs.formRef.validate((valid, errors) => {
        if (valid) {
          this.loading = true
          const data = this.form;
          return createItem(data)
              .then((response) => {
                this.$emit('insertSuccess');
                ElMessage.success("插入成功");
                this.clearAll();
                this.loading = false;
              })
              .catch((error) => {
                ElMessage.error("插入失败");
                console.log(error);
              });
        }
        else {
          ElMessage.warning("请检查你的输入")
          console.log(errors)
        }
      })
    },

    clearAll() {
      this.form = {
        name: '',
        price: '',
        stock: '',
        itemCategoryId: '',
        description: '',
      }
    },

  },
}


</script>

<style scoped>
.box {
  width: 1200px;
  display: inline-block;
}
</style>